

"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"
"jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}"


var router = require('express').Router();
const { default: axios } = require('axios');
var webResult = require('../web-result');
var crypto = require("crypto");


let access_token = null;
let jsapi_ticket = null;
async function refreshAccessToken()
{
    const appid = "wx4de03f4789e8d032"
    const secret = "745abf1fca4698387461259f3ba71826";
    const response = await axios({
        method: "GET",
        url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`
    });
    const result = response.data;
    if (result.errcode)
    {
        console.error(result.errmsg);
        return;
    }
    access_token = result.access_token;
}
async function refreshJSAPITicket()
{
    const response = await axios({
        method: "GET",
        url: `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`
    });
    const result = response.data;
    jsapi_ticket = result.ticket;
}


axios({
    method: "GET",
    url: "http://cyue.net/api/tool/x-real-ip"
}).then(async response => {
    const result = response.data;
    const ip = result.data;
    console.log("ip:", ip);
    if (ip === "121.40.119.36")
    {
        await refreshAccessToken();
        await refreshJSAPITicket();
        console.log("wx access_token:", access_token);
        console.log("wx jsapi_ticket:", jsapi_ticket);
        // 定时刷新 access_token
        setInterval(
            async () => {
                await refreshAccessToken();
                await refreshJSAPITicket();
                console.log("wx access_token:", access_token);
                console.log("wx jsapi_ticket:", jsapi_ticket);
            },
            1000 * 6000
        )
    }
});




router.post("/wx/signature", async (request, response) => {

    if (!jsapi_ticket)
    {
        response.send(webResult.failed(undefined, "内部错误"));
        return;
    }

    const { url } = request.body;
    if (!url)
    {
        response.send(webResult.failed(undefined, "url为空"));
        return;
    }

    const timestamp = new Date().getTime();
    const noncestr = "cyue";
    const string1 = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`
    const signature = crypto.createHash("sha1").update(string1).digest("hex");

    response.send(webResult.success({
        url: url,
        timestamp: timestamp,
        nonceStr: noncestr,
        signature: signature
    }));
});



module.exports = router;


